/*
 * @Date: 2022-11-08 13:07:28
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-11-29 14:38:13
 * @FilePath: \vue-admin-ts\src\store\login\index.ts
 * @Description: store of login
 */
import { Module } from "vuex";
import type { IRootState } from "../type";
import { mapMenuToRoutes, mapMenusToPermissions } from "@/utils/mapMenus";
import router from "@/router";
import {
  loginByAccount,
  reqUserInfoById,
  reqUserMenusByRoleId,
} from "@/apis/login/login";
export interface ILoginState {
  token: string;
  userInfo: any;
  userMenus: [];
  permissions: string[];
}
const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state: () => {
    return {
      token: "",
      userInfo: {},
      userMenus: [],
      permissions: [],
    };
  },
  actions: {
    async accountLoginAction(
      { commit },
      payload: { userName: string; password: string },
    ) {
      const { userName, password } = payload;
      const accoutRes = await loginByAccount({ name: userName, password });
      window.localStorage.setItem("token", accoutRes.data.token);
      const userInfoRes = await reqUserInfoById(accoutRes.data.id);
      const userInfo = userInfoRes.data;
      window.localStorage.setItem("userInfo", JSON.stringify(userInfo));
      commit("changeToken", accoutRes.data.token);
      commit("changeUserInfo", userInfo);

      //请求用户菜单
      const userRoleMenus = await reqUserMenusByRoleId(userInfo.role.id);
      window.localStorage.setItem(
        "userMenus",
        JSON.stringify(userRoleMenus.data),
      );
      commit("changeUserMenus", userRoleMenus.data);
      //跳转
      router.push("/main");
    },
    loadLocalState({ commit }) {
      const token = localStorage.getItem("token");
      if (token) {
        commit("changeToken", token);
      }
      let userInfo = localStorage.getItem("userInfo");
      if (userInfo) {
        userInfo = JSON.parse(userInfo);
        commit("changeUserInfo", userInfo);
      }
      const userMenus = localStorage.getItem("userMenus");
      if (userMenus) {
        commit("changeUserMenus", JSON.parse(userMenus));
      }
    },
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token;
    },
    changeUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
    changeUserMenus(state, userMenus) {
      state.userMenus = userMenus;
      const routes = mapMenuToRoutes(userMenus);
      // console.log("store userMenus", routes);
      routes.forEach((item) => {
        router.addRoute("main", item);
      });
      const permissions = mapMenusToPermissions(userMenus);
      state.permissions = permissions;
    },
  },
  getters: {},
};
export default loginModule;
